/*
 Copyright (C) 2010 Chris Hawkins. All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 
 * Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.
 
 * Neither the name of the author nor the names of its contributors may be used
 to endorse or promote products derived from this software without specific
 prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#import "AsdMacro.h"
#import "AsdParse.h"
#import "AsdParseDef.h"
#import "AsdConst.h"

@implementation ASDPrBase
#pragma mark -- NSXMLParser parse and results
@synthesize matchRequestId    = match_RequestId,    matchBoxUsage        = match_BoxUsage;
@synthesize parseElementCount = parse_ElementCount, parseMaxElementDepth = parse_MaxElementDepth;
@synthesize parseError        = parse_Error;
- (NSArray*)        matchErrors {
    NSArray *match = ( match_Errors == nil ? nil : [[NSArray alloc] initWithArray: match_Errors] );
return [match autorelease];
}
- (BOOL)            parseData: (NSData*) xmlData_ {
    BOOL        success = FALSE;
    do {
        if ( xmlData_ == nil || 0 == [xmlData_ length]  ) {
            break;
        }
        if ( xmlParser != nil || 0 < parse_ElementCount ) {      // Not setup for reuse
            break;
        }
        if ( parse_Error != nil || parse_Exception != nil ) {
            break;
        }
        xmlParser = [[NSXMLParser alloc] initWithData: xmlData_];
        [xmlParser setDelegate: self];
        @try {
            success = [xmlParser parse];
        }
        @catch (NSException* e) {
            NSLog( @"NSXMLParse NSException: %@ reason: %@", [e name],[e reason] );
            parse_Exception = [e retain];
        }
        @finally {
            [xmlParser release];
            xmlParser = nil;
        }
        
    } while ( false );
    return success;
}
#pragma mark -- Methods normally overridden by derived classes
+ (ASDPrElementDictionary*) elementDictionary {
    return [ASDPrDef dictionaryBase];
}
#pragma mark -- Derived classes override for specific elements, but standard elements handled here
- (void)            parseStartElement: (NSUInteger) elementCode_ definition: (ASDPrElement*) elementDef_  attributes: (NSDictionary*) attributeDict_ {
    do {
        if ( elementCode_ == eASDPrElement_Errors ) {
            if ( match_Errors == nil ) {
                match_Errors = [[NSMutableArray alloc] initWithCapacity: 4];
            }
            break;
        }
        if ( elementCode_ == eASDPrElement_Error ) {
            [self stackPokeObject: [NSMutableDictionary dictionaryWithCapacity: 4]];
            break;
        }
    } while( FALSE );
}
- (void)            parseFoundCharacters: (NSUInteger) elementCode_ characters: (NSString*) string_ {
    do {
        if ( elementCode_ == eASDPrElement_BoxUsage ) {
            match_BoxUsage = [string_ floatValue];
            break;
        }
        if ( elementCode_ == eASDPrElement_RequestId ) {
            [match_RequestId release];
            match_RequestId = [string_ retain];
            break;
        }
        if ( elementCode_ == eASDPrElement_Code || elementCode_ == eASDPrElement_Message ) {
            NSMutableDictionary  *userInfo = (NSMutableDictionary*) [self stackObjectForCode: eASDPrElement_Error];
            if ( userInfo != nil ) {
                [userInfo setObject: string_ 
                             forKey: ( elementCode_ == eASDPrElement_Code ? NSLocalizedFailureReasonErrorKey : NSLocalizedDescriptionKey )];
            }
        }
    } while ( FALSE );
}
- (void)            parseEndElement: (NSUInteger) elementCode_ {
    if ( elementCode_ == eASDPrElement_Error ) {
        NSMutableDictionary  *userInfo = (NSMutableDictionary*) [self stackPeekObject];
        NSString             *errorId  = [userInfo objectForKey: NSLocalizedFailureReasonErrorKey];
        ASDPrElement         *element  = [[ASDPrDef dictionaryAPIErrors] elementByName: errorId];
        NSUInteger            code     = ( element == nil ? eASDPrAPIError_INVALID : [element code] );
        [match_Errors addObject: [NSError errorWithDomain: [ASDSpConst asdErrorDomain] code: code userInfo: userInfo]];
    }
}
#pragma mark -- NSObject standard
- (id)              initWithElementDictionary: (ASDPrElementDictionary*) elementDictionary_ {
    if ( self = [super init] ) {
        elementDictionary = [elementDictionary_ retain];
    }
    return self;
}
- (void)            dealloc {
    [self stackClear];
    [elementDictionary release];
    [match_RequestId   release];
    [match_Errors      release];
    [parse_Error       release];
    [parse_Exception   release];
    [super dealloc];
}

#pragma mark -- Parse Stack
- (void)            stackClear {
    while ( 0 < parseStackCount ) {
        [self stackPop: NULL];
    }
}
- (NSUInteger)      stackCount {
    return parseStackCount;
}
- (NSUInteger)      stackCountMax {
    return mASDarrayCount( parseStack );
}
- (BOOL)            stackIsFull {
    return ( mASDarrayCount( parseStack ) <= parseStackCount );
}
- (NSObject*)       stackObjectForCode: (NSUInteger) parentElementCode_ {
    NSObject*   match = nil;
    for (NSInteger index = (parseStackCount -2); 0 <= index; index-- ) { // Do not match on top of stack, only ancestors
        if ( parseStack[ index ].elementCode == parentElementCode_ ) {
            match = parseStack[ index ].elementObject;
            break;
        }
    }
    return match;
}
- (NSUInteger)      stackPeekCode {
    return ( 0 == parseStackCount ? 0 : parseStack[ parseStackCount -1 ].elementCode );
}
- (NSUInteger)      stackPeekCodeParent {
    return ( parseStackCount < 2 ? 0 : parseStack[ parseStackCount -2 ].elementCode );
}
- (NSObject*)       stackPeekObject {
    return ( 0 == parseStackCount ? nil : parseStack[ parseStackCount -1 ].elementObject );
}
- (void)            stackPokeObject: (NSObject*) pokeObject {
    if ( 0 < parseStackCount ) {
        stASDParseStack *cur = &parseStack[ (parseStackCount -1) ];
        mASDreleaseNil( cur->elementObject );
        if ( pokeObject != nil ) {
            cur->elementObject = [pokeObject retain];
        }
    } else {
        if ( pokeObject != nil ) {
            NSLog( @"Invalid call to %@ - stack is empty", NSStringFromSelector(_cmd));
        }
    }
}
- (NSUInteger)      stackPop: (NSObject**) pObject_ {
    NSUInteger  code    = 0;
    if ( pObject_ != nil ) {
        mASDreleaseNil( *pObject_ );
    }
    if ( 0 < parseStackCount ) {
        stASDParseStack *cur = &parseStack[ --parseStackCount ];
        if ( pObject_ != nil ) {
            *pObject_ = [cur->elementObject retain];  
        }
        code = cur->elementCode;
        cur->elementCode    = 0;
        mASDreleaseNil( cur->elementObject );
    }
    return code;
}
- (void)            stackPush: (NSObject*) pushObject_ code: (NSUInteger) pushCode_ {
    if ( parseStackCount < [self stackCountMax] ) {
        stASDParseStack *cur = &parseStack[ parseStackCount++ ];
        cur->elementCode    = pushCode_;
        if ( pushObject_ != nil ) {
            cur->elementObject  = [pushObject_ retain];            
        }
    }
}
@end
